package com.atguigu.shiro.realms;

import org.apache.shiro.authc.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;

public class SecondRealm extends AuthenticatingRealm {


    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {

         System.out.println("SecondRealm");

        //1、把AuthenticationToken对象转换为UsernamePasswordToken对象
        UsernamePasswordToken u = (UsernamePasswordToken) authenticationToken;
        //2、从UsernamePasswordToken获取username和password
        String username = u.getUsername();
        //3、调用数据库的方法，从数据库中查询用户的记录☆
        System.out.println("从数据库中获取用户信息" + username);
        //4、若用户不存在，则抛出UnknownAccountException
        if ("unknown".equals(username)) {
            throw new UnknownAccountException("用户不存在");
        }
        //5、根据用户的情况，抛出其他AuthenticationException异常
        if ("monster".equals(username)) {
            throw new LockedAccountException("用户被锁定");
        }

        //6、根据用户的情况，构建AuthenticationInfo对象并返回，通常使用的实现类是SimpleAuthenticationInfo
        //以下信息从数据库中获取
        //1）principal：认证的实体信息，可以是username也可以是数据表对应的实体类对象
        Object principal = username;
        //2)credentials：密码
        Object credentials = null;
        if("admin".equals(username)){
            credentials = "ce2f6417c7e1d32c1d81a797ee0b499f87c5de06-";
        }else if("user".equals(username)){
            credentials = "073d4c3ae812935f23cb3f2a71943f49e082a718-";
        }
        //Object credentials = "fc1709d0a95a6be30bc5926fdb7f22f4";//该密码从数据库中获取
        //3)realmName:当前realm对象的name,调用父类getName()方法即可。
        String realmName = getName();
        //4)盐值
        ByteSource credentialSalt = ByteSource.Util.bytes(username);//将用户名作为盐，因为用户名唯一。
        SimpleAuthenticationInfo info = null;//new SimpleAuthenticationInfo(principal, credentials, realmName);
        info =  new SimpleAuthenticationInfo(principal, credentials,credentialSalt, realmName);
        return info;
    }

    public static void main(String[] args) {
        String hashAlgorithmName = "SHA1";
        Object credentials = "123456";
        Object salt = ByteSource.Util.bytes("user");
        int hashIterations = 1024;
        Object result = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
        System.out.println(result);//fc1709d0a95a6be30bc5926fdb7f22f4
    }
}
